import { to as tos } from 'await-to-js';
import router from './router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getToken } from '@/utils/auth';
import { isHttp, isPathMatch } from '@/utils/validate';
import { isRelogin } from '@/utils/request';
import { useUserStore } from '@/store/modules/user';
import { useSettingsStore } from '@/store/modules/settings';
import { usePermissionStore } from '@/store/modules/permission';
import { ElMessage } from 'element-plus/es';

NProgress.configure({ showSpinner: false });
const whiteList = ['/login', '/register', '/social-callback', '/register*', '/register/*'];

const isWhiteList = (path: string) => {
  return whiteList.some((pattern) => isPathMatch(pattern, path));
};

router.beforeEach(async (to, from, next) => {
  console.log('🚀 Router beforeEach triggered:', { to: to.path, from: from.path });
  NProgress.start();
  
  // 设置页面标题
  to.meta.title && useSettingsStore().setTitle(to.meta.title as string);
  
  // 跳过所有鉴权逻辑，确保路由已生成
  if (usePermissionStore().getSidebarRoutes().length === 0) {
    console.log('🔄 Generating routes for first time...');
    isRelogin.show = false;
    const routes = await usePermissionStore().generateRoutes();
    console.log('✅ Routes generated:', routes);
    console.log('📋 Sidebar routes:', usePermissionStore().getSidebarRoutes());
  }
  
  // 直接允许访问所有页面
  next();
});

router.afterEach(() => {
  NProgress.done();
});
